﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class administration_listServiceProfile : System.Web.UI.Page
{
    private string IDEN, UPDATEPARAM, NEWPARAM, MESSAGEPARAM, DELETEPARAM, PATHIMAGE = System.Configuration.ConfigurationSettings.AppSettings["pathImage"], idClient = "";
    private const string IDPAGE = "0";

    protected void Page_Load(object sender, EventArgs e)
    {
        //Check the status of the session
        STATE_SESSION();

        //Verify the view that corresponds show
        if (!Page.IsPostBack)
        {
            string flgInsert = Request.Cookies.Get("flgInsert").Value;
            string flgUpdate = Request.Cookies.Get("flgUpdate").Value;
            string flgDelete = Request.Cookies.Get("flgDelete").Value;

            this.IDEN = Request.Params.Get("id");
            this.NEWPARAM = Request.Params.Get("new");
            this.UPDATEPARAM = Request.Params.Get("update");
            this.MESSAGEPARAM = Request.Params.Get("message");
            this.DELETEPARAM = Request.Params.Get("delete");

            if (this.NEWPARAM != null)
            {
                MServiceProfile.ActiveViewIndex = 1;
            }
            else
            {
                if (this.UPDATEPARAM != null)
                {
                    MServiceProfile.ActiveViewIndex = 2;
                }
                else
                {
                    if (this.MESSAGEPARAM != null)
                    {
                        MServiceProfile.ActiveViewIndex = 3;
                        String nameupdate = Request.Params.Get("nameupdate");
                        String namenew = Request.Params.Get("namenew");
                        String removal = Request.Params.Get("removal");
                        if (namenew != null)
                        {
                            this.lblMessage.Text = "Se ha registrado con exito a: " + namenew;
                        }
                        else
                        {
                            if (nameupdate != null)
                            {
                                this.lblMessage.Text = "La modificacion ha sido exitosa.";
                            }
                            else
                            {
                                if (removal != null)
                                {
                                    if (removal.Equals("yes"))
                                    {
                                        this.lblMessage.Text = "La eliminacion ha sido exitosa.";
                                    }
                                    else
                                    {
                                        this.lblMessage.Text = "El registro esta siendo usado, por este motivo no puede ser eliminado.";
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if (this.DELETEPARAM != null)
                        {
                            this.DeleteRecord(this.IDEN);
                        }
                        MServiceProfile.ActiveViewIndex = 0;
                    }
                }
            }
            intPageSize.Text = "10"; //Here indicates the size of the page
            intCurrIndex.Text = "0";
            idClient = Request.Params.Get("idClient");
            if (idClient == null) {
                idClient = Request.Cookies.Get("ClientID").Value;
            } else {
                //creamos la cookie para utilizarla siempre                
                HttpCookie objCookie = new HttpCookie("ClientID", idClient);
                Response.Cookies.Add(objCookie);
                                
            }

            Bind(idClient,"0","0");
            //Disable the checks after loading the datalist
            UpdateInsertDelete(flgUpdate, flgInsert, flgDelete);
            //Built the menu according to user roles
            BuildMenu();
        }
    }

    //Method to verify the status of the current session
    public void STATE_SESSION()
    {
        if (!Page.IsPostBack)
        {
            HttpCookie state = Request.Cookies.Get("state");
            if (state == null)
                Response.Redirect("../index.aspx");
        }
    }

    //Method to verify the user's role
    private void UpdateInsertDelete(string update, string insert, string delete)
    {
        if (!insert.Equals("1"))
        {
            lnkNew.Enabled = false;
        }
        if (!update.Equals("2"))
        {
            foreach (DataListItem item in DataList1.Items)
            {
                HyperLink hp = null;
                hp = (HyperLink)item.FindControl("lnkUpdate");
                if (hp != null)
                {
                    hp.Enabled = false;
                }
            }
        }
        if (!delete.Equals("3"))
        {
            foreach (DataListItem item in DataList1.Items)
            {
                HyperLink hp = null;
                hp = (HyperLink)item.FindControl("lnkDelete");
                if (hp != null)
                {
                    hp.Enabled = false;
                }
            }
        }
    }

    //Method to build menu
    private void BuildMenu()
    {
        string programName = Request.Cookies.Get("programName").Value;
        char[] delimiterChars = { ',' };
        string[] vectorProgramName = programName.Split(delimiterChars);
        string welcome = "";
        string segurity = "";
        string system = "";
        string parameters = "";
        string people = "";
        string operations = "";
        string reports = "";
        string profile = "";
        for (int i = 0; i < vectorProgramName.Length; i++)
        {
            switch (Convert.ToInt32(vectorProgramName[i]))
            {
                case 1:
                    people += "<li><a class=\"item\" href=\"listNaturalPersons.aspx\"> - Personas Naturales</a></li>";
                    break;
                case 2:
                    people += "<li><a class=\"item\" href=\"listLegalPersons.aspx\"> - Personas Legales</a></li>";
                    break;
                case 3:
                    welcome += "<li><a class=\"item\" href=\"index.aspx\"> - Bienvenido</a></li>";
                    break;
                case 4:
                    parameters += "";
                    break;
                case 5:
                    system += "<li><a class=\"item\" href=\"listLogTransaction.aspx\"> - Log de Transacciones</a></li>";
                    break;
                case 6:
                    operations += "<li><a class=\"item\" href=\"listNews.aspx\"> - Boletines</a></li>";
                    break;
                case 7:
                    operations += "<li><a class=\"item\" href=\"listClient.aspx\"> - Clientes</a></li>";
                    break;
                case 8:
                    segurity += "<li><a class=\"item\" href=\"listProfiles.aspx\"> - Perfiles</a></li>";
                    break;
                case 9:
                    system += "<li><a class=\"item\" href=\"listPrograms.aspx\"> - Programas</a></li>";
                    break;
                case 10:
                    operations += "<li><a class=\"item\" href=\"listCourse.aspx\"> - Cursos</a></li>";
                    break;
                case 11:
                    segurity += "<li><a class=\"item\" href=\"listRoles.aspx\"> - Roles</a></li>";
                    break;
                case 12:
                    segurity += "<li><a class=\"item\" href=\"listUsers.aspx\"> - Usuarios</a></li>";
                    break;
                case 13:
                    reports += "<li><a class=\"item\" href=\"reports.aspx\"> - Clientes por tipo de Servicio</a></li>";
                    break;
                case 14:
                    system += "<li><a class=\"item\"href=\"listWorkArea.aspx\"> - Areas</a></li>";
                    break;
                case 15:
                    parameters += "<li><a class=\"item\"href=\"listMode.aspx\"> - Modalidades</a></li>";
                    break;
                case 16:
                    parameters += "<li><a class=\"item\"href=\"listProfession.aspx\"> - Profesiones</a></li>";
                    break;
                case 17:
                    operations += "<li><a class=\"item\"href=\"listPublicity.aspx\"> - Publicidades</a></li>";
                    break;
                case 18:
                    operations += "<li><a class=\"item\"href=\"listQuestionAnswer.aspx\"> - Consultas del Cliente</a></li>";
                    break;
                case 19:
                    parameters += "<li><a class=\"item\"href=\"listService.aspx\"> - Servicios</a></li>";
                    break;                
                case 21:
                    operations += "<li><a class=\"item\"href=\"listServiceProfileClient.aspx\"> - Perfiles de Clientes</a></li>";
                    break;
                case 22:
                    operations += "<li><a class=\"item\"href=\"listSponsor.aspx\"> - Auspiciadores</a></li>";
                    break;
                case 23:
                    parameters += "<li><a class=\"item\"href=\"listYear.aspx\"> - Gestiones</a></li>";
                    break;
                case 24:
                    profile += "<li><a class=\"item\"href=\"listProfileClientService.aspx\"> - Servicios</a></li>";
                    break;
                case 25:
                    profile += "<li><a class=\"item\"href=\"listProfileClientCourse.aspx\"> - Cursos</a></li>";
                    break;
                case 26:
                    operations += "<li><a class=\"item\"href=\"listClientCourse.aspx\"> - Cursos del Cliente</a></li>";
                    break;
                case 27:
                    profile += "<li><a class=\"item\"href=\"listProfileQA.aspx\"> - Consultas</a></li>";
                    break;
            }
        }
        lblMenu.Text = "<div class=\"left\"><ul class=\"title\"><li>Menu Administrativo</li></ul><ul id=\"menu\"><li>";
        lblMenu.Text += "<a href=\"#\">Bienvenido</a><ul>";
        lblMenu.Text += welcome;
        lblMenu.Text += "</ul></li>";
        if (!segurity.Equals("")) {
            lblMenu.Text += "<li><a href=\"#\">Gestion de Seguridad</a><ul>";
            lblMenu.Text += segurity;
            lblMenu.Text += "</ul></li>";
        }
        if (!system.Equals("")) {
            lblMenu.Text += "<li><a href=\"#\">Gestion del Sistema</a><ul>";
            lblMenu.Text += system;
            lblMenu.Text += "</ul></li>";
        }
        if (!parameters.Equals("")) {
            lblMenu.Text += "<li><a href=\"#\">Gestion de Parametros</a><ul>";
            lblMenu.Text += parameters;
            lblMenu.Text += "</ul></li>";
        }
        if (!people.Equals("")) {
            lblMenu.Text += "<li><a href=\"#\">Gestion de Personas</a><ul>";
            lblMenu.Text += people;
            lblMenu.Text += "</ul></li>";
        }
        if (!operations.Equals("")) {
            lblMenu.Text += "<li><a href=\"#\">Gestion de Operaciones</a><ul>";
            lblMenu.Text += operations;
            lblMenu.Text += "</ul></li>";
        }
        if (!profile.Equals("")) {
            lblMenu.Text += "<li><a href=\"#\">Perfil del Cliente</a><ul>";
            lblMenu.Text += profile;
            lblMenu.Text += "</ul></li>";
        }
        if (!reports.Equals("")) {
            lblMenu.Text += "<li><a href=\"#\">Reportes</a><ul>";
            lblMenu.Text += reports;
            lblMenu.Text += "</ul></li>";
        }
        lblMenu.Text += "<li><a href=\"../index.aspx\">Salir</a></li>";
        lblMenu.Text += "</ul></div>";
    }

    //Method to enable calendar
    protected void PopCalendar_SelectionChanged(object sender, EventArgs e)
    {
        this.Validate("RJS.PopCalendars");
    }

    //Method to cancel the view NEW
    protected void lnkCancel_Click(object sender, EventArgs e)
    {
        MServiceProfile.ActiveViewIndex = 0;
    }

    //Method to cancel the view UPDATE
    protected void lnkCancel_Click1(object sender, EventArgs e)
    {
        MServiceProfile.ActiveViewIndex = 0;
    }

    #region Pager

    //Method to query data and create the pager
    private void Bind(String txtIdClient, String txtIdService, String txtIdYear)
    {
        DataSet objDS = new DataSet();
        clsServiceProfile obj = new clsServiceProfile();
        LabelClient(txtIdClient);
        if (!Page.IsPostBack)
        {
            objDS = obj.SeeAllTheRecords(0, 0, txtIdClient, txtIdService, txtIdYear);
            intRecordCount.Text = objDS.Tables[0].Rows.Count + "";
            objDS = null;
            objDS = new DataSet();
        }

        if (intCurrIndex.Text.Equals("0"))
        {
            hrefPrevious.Visible = false;
        }
        else
        {
            hrefPrevious.Visible = true;
        }

        objDS = obj.SeeAllTheRecords(Int32.Parse(intCurrIndex.Text), Int32.Parse(intPageSize.Text), txtIdClient, txtIdService, txtIdYear);

        DataList1.DataSource = objDS.Tables[0].DefaultView;
        DataList1.DataBind();
        PrintStatus();
    }

    //Method to navigate to the first page of pager
    public void ShowFirst(object sender, EventArgs e)
    {
        intCurrIndex.Text = "0";
        idClient = Request.Cookies.Get("ClientID").Value;
        string service = this.cbServiceList.SelectedValue;
        string year = this.cbYearList.SelectedValue;
        Bind(idClient,service,year);
    }

    //Method to navigate to the previous page in the pager
    public void ShowPrevious(object sender, EventArgs e)
    {
        intCurrIndex.Text = (Int32.Parse(intCurrIndex.Text) - Int32.Parse(intPageSize.Text)) + "";
        if (Int32.Parse(intCurrIndex.Text) < 0)
        {
            intCurrIndex.Text = "0";
        }
        idClient = Request.Cookies.Get("ClientID").Value;
        string service = this.cbServiceList.SelectedValue;
        string year = this.cbYearList.SelectedValue;
        Bind(idClient,service,year);
    }

    //Method to navigate to the next page in the pager
    public void ShowNext(object sender, EventArgs e)
    {
        if ((Int32.Parse(intCurrIndex.Text) + 1) < Int32.Parse(intRecordCount.Text))
        {
            intCurrIndex.Text = (Int32.Parse(intCurrIndex.Text) + Int32.Parse(intPageSize.Text)) + "";
        }
        idClient = Request.Cookies.Get("ClientID").Value;
        string service = this.cbServiceList.SelectedValue;
        string year = this.cbYearList.SelectedValue;
        Bind(idClient,service,year);
    }

    //Method to navigate to the last page of the pager
    public void ShowLast(object sender, EventArgs e)
    {
        int tmpInt = 0;
        tmpInt = Int32.Parse(intRecordCount.Text) % Int32.Parse(intPageSize.Text);
        if (tmpInt > 0)
        {
            intCurrIndex.Text = (Int32.Parse(intRecordCount.Text) - tmpInt) + "";
        }
        else
        {
            intCurrIndex.Text = (Int32.Parse(intRecordCount.Text) - Int32.Parse(intPageSize.Text)) + "";
        }
        idClient = Request.Cookies.Get("ClientID").Value;
        string service = this.cbServiceList.SelectedValue;
        string year = this.cbYearList.SelectedValue;
        Bind(idClient,service,year);
    }

    //Method to generate the data pager navigation
    private void PrintStatus()
    {
        lblTotal.Text = "Total de Registros:<b> " + intRecordCount.Text + "</b>";
        lblShowing.Text = "Mostrando Pagina:<b> ";
        lblShowing.Text += ((Int32.Parse(intCurrIndex.Text) / Int32.Parse(intPageSize.Text)) + 1) + "";
        lblShowing.Text += "</b> de <b>";

        if ((Int32.Parse(intRecordCount.Text) % Int32.Parse(intPageSize.Text)) > 0)
        {
            lblShowing.Text += ((Int32.Parse(intRecordCount.Text) / Int32.Parse(intPageSize.Text)) + 1) + "";
        }
        else
        {
            lblShowing.Text += (Int32.Parse(intRecordCount.Text) / Int32.Parse(intPageSize.Text)) + "";
        }
        lblShowing.Text += "</b>";
    }
    #endregion

    

    //Method to insert a record in the view NEW
    protected void lnkInsert_Click(object sender, EventArgs e)
    {
        if (Page.IsValid == true)
        {
            clsServiceProfile obj = new clsServiceProfile();
            obj.IdService = Convert.ToInt32(cbService.SelectedValue);
            string id = Request.Cookies.Get("ClientID").Value;
            obj.IdClient = Convert.ToInt32(id);
            obj.IdYear = Convert.ToInt32(cbYear.SelectedValue);
            obj.IdMode = Convert.ToInt32(cbMode.SelectedValue);
            obj.DtDate = txtDate.Text.Replace('-', '/').Substring(0, 10);
            obj.SMonth = cbMonth.SelectedValue;
            clsClient objClient = new clsClient();
            DataSet dtClient = objClient.ConsultID(id);
            obj.SNameClient = dtClient.Tables[0].Rows[0].ItemArray[3] + "";
            clsService objService = new clsService();
            DataSet dtService = objService.ConsultID(cbService.SelectedValue);
            string NameService = dtService.Tables[0].Rows[0].ItemArray[1] + "";
            obj.SNameService = NameService;
            obj.ICompleted = Convert.ToInt32(rbCompleted.SelectedValue);
            obj.Insert();

            Response.Redirect("listServiceProfile.aspx?message=yes&namenew=" + NameService );
        }
        else
        {
            lblMsgValidatorNew.Text = "Algunos campos no son validos.";
        }
    }

    //Method to return the view according to the message
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        if ((Request.Params.Get("nameupdate") != null) || (Request.Params.Get("removal") != null))
            Response.Redirect("listServiceProfile.aspx");
        else
            Response.Redirect("listServiceProfile.aspx?new=yes");
    }

    //Method to update a record in the view UPDATE
    protected void lnkUpdate_Click(object sender, EventArgs e)
    {
        if (Page.IsValid == true)
        {
            HiddenField fhidID = (HiddenField)frmvUpdateServiceProfile.FindControl("hidID");            
            DropDownList fcbService = (DropDownList)frmvUpdateServiceProfile.FindControl("cbService");
            DropDownList fcbYear = (DropDownList)frmvUpdateServiceProfile.FindControl("cbYear");
            DropDownList fcbMode = (DropDownList)frmvUpdateServiceProfile.FindControl("cbMode");
            DropDownList fcbMonth = (DropDownList)frmvUpdateServiceProfile.FindControl("cbMonth");
            TextBox ftxtName = (TextBox)frmvUpdateServiceProfile.FindControl("txtName");            
            TextBox ftxtUrlImage = (TextBox)frmvUpdateServiceProfile.FindControl("txtUrlImage");
            TextBox ftxtDate = (TextBox)frmvUpdateServiceProfile.FindControl("txtDate");
            RadioButtonList frbCompleted = (RadioButtonList)frmvUpdateServiceProfile.FindControl("rbCompleted");

            clsServiceProfile obj = new clsServiceProfile();
            obj.ID = Convert.ToInt32(fhidID.Value);
            obj.IdService = Convert.ToInt32(fcbService.SelectedValue);
            string id = Request.Cookies.Get("ClientID").Value;
            obj.IdClient = Convert.ToInt32(id);
            obj.IdYear = Convert.ToInt32(fcbYear.SelectedValue);
            obj.IdMode = Convert.ToInt32(fcbMode.SelectedValue);
            obj.DtDate = ftxtDate.Text.Replace('-', '/').Substring(0, 10);
            obj.SMonth = fcbMonth.SelectedValue;
            clsClient objClient = new clsClient();
            DataSet dtClient = objClient.ConsultID(id);
            obj.SNameClient = dtClient.Tables[0].Rows[0].ItemArray[3] + "";
            clsService objService = new clsService();
            DataSet dtService = objService.ConsultID(fcbService.SelectedValue);
            string NameService = dtService.Tables[0].Rows[0].ItemArray[1] + "";
            obj.SNameService = NameService;
            obj.ICompleted = Convert.ToInt32(frbCompleted.SelectedValue);
            obj.Update();

            Response.Redirect("listServiceProfile.aspx?message=yes&nameupdate=" + NameService );
        }
        else
        {
            lblMsgValidatorNew.Text = "Algunos campos no son validos.";
        }
    }

    //Method for the disposal of records
    private void DeleteRecord(String id)
    {        
        clsServiceProfile obj = new clsServiceProfile();
        obj.ID = Convert.ToInt32(id);
        obj.Delete();
        Response.Redirect("listServiceProfile.aspx?message=yes&removal=yes");
    }

    protected void cbService_SelectedIndexChanged(object sender, EventArgs e) {
        string service = this.cbServiceList.SelectedValue;
        string year = this.cbYearList.SelectedValue;
        if (service.Equals("1")) { service = "0"; }
        if (year.Equals("1")) { year = "0"; }
        idClient = Request.Cookies.Get("ClientID").Value;
        Bind(idClient,service,year);
    }
    protected void cbYear_SelectedIndexChanged(object sender, EventArgs e) {
        string service = this.cbServiceList.SelectedValue;
        string year = this.cbYearList.SelectedValue;
        if (service.Equals("1")) { service = "0"; }
        if (year.Equals("1")) { year = "0"; }
        idClient = Request.Cookies.Get("ClientID").Value;
        Bind(idClient,service,year);
    }
    public void LabelClient(string id) {
        clsClient objClient = new clsClient();
        DataSet dtClient = objClient.ConsultID(id);
        lblCliente.Text = dtClient.Tables[0].Rows[0].ItemArray[3] + "";
    }
}
